import { getDelateTargetByClassName } from "../helper";
import type { EaseTabs } from "../index";

export class TabEvent {
    eTabs: EaseTabs;
    tab: Element | undefined;
    overTab: Element | undefined;
    tabWrap: HTMLUListElement | undefined;
    drag = false;
    
    constructor(eTabs: EaseTabs){
        this.eTabs = eTabs;
    }


    registerCopy(tabWrap:HTMLUListElement) {
        
        tabWrap?.addEventListener("contextmenu", (e) => {
            e.preventDefault(); // 阻止默认的右键菜单显示
            const tab = getDelateTargetByClassName(e.target as Element, this.eTabs.names.tabClassName)!;
            const tip = tab.getAttribute("data-tip") as string;
            navigator.clipboard.writeText(tip);
        });
        tabWrap.addEventListener("dblclick", (e) => {
            const tab = getDelateTargetByClassName(e.target as Element, this.eTabs.names.tabClassName)!;
            const tip = tab.getAttribute("data-tip") as string;
            navigator.clipboard.writeText(tip);
        })
    }

    registerMouseClick(tabWrap:HTMLUListElement, changeFn: any, closeFn:any) {
        tabWrap.addEventListener("click", (e) => {
            const tab = getDelateTargetByClassName(e.target as Element, this.eTabs.names.tabContainerClassName)!;
            const close = getDelateTargetByClassName(e.target as Element, `${this.eTabs.names.tabClassName}-close`);
            if (close) {
                closeFn && closeFn(tab);
                return;
            } 
            tab && changeFn && changeFn(tab);
        })
    }
    
    // 记录起始位置
    record (eleAll) {
        for (let i = 0 ;i < eleAll.length;i ++) {
            const { top, left } = eleAll[i].getBoundingClientRect();
            eleAll[i]._top = top;
            eleAll[i]._left = left;
        }
    }
    // 记录最后的位置，并执行动画
    last (eleAll) {
        for (let i = 0;i < eleAll.length;i ++) {
            const dom = eleAll[i] ? eleAll[i] : this.tabWrap?.children[1];
            const { top, left } = dom.getBoundingClientRect();
            if (dom._left) {
                dom.style.transform = `translate3d(${dom._left-left}px,${dom._top-top}px,0px)`;
                let rafId = requestAnimationFrame(function() {
                    dom.style.transition = 'transform 0.3s ease-out';
                    dom.style.transform = 'none';
                })
                dom.addEventListener('transitionend',() => {
                    dom.style.transition = 'none';
                    cancelAnimationFrame(rafId);
                })
            }
        }
    }

    registerDrag(tabWrap:HTMLUListElement) {
        this.tabWrap = tabWrap;
        // 判断当前拖动的是哪个元素
        let source_node;
        tabWrap.addEventListener("dragstart", (e: any) => {
            // 要操作的元素
            this.tab = getDelateTargetByClassName(e.target as Element, this.eTabs.names.tabContainerClassName)!;
            // 获取当前拖动的元素
            source_node = this.tab;
            // 记录起始位置
            this.record(this.tab);
            setTimeout(() => {
                this.tab!.classList.add(`${this.eTabs.names.tabContainerClassName}-dragging`);
            }, 0);
            if (e.dataTransfer?.effectAllowed) {
                e.dataTransfer.effectAllowed = 'move';
            }
        });
        tabWrap.addEventListener("dragenter",(e: any) => {
            this.overTab = getDelateTargetByClassName(e.target as Element, this.eTabs.names.tabContainerClassName)!;
            e.preventDefault();
            // 拖回到原来的位置，就什么也不做
            if(this.overTab === tabWrap || this.overTab === source_node) {
                return false;
            }
            // 获取.list的所有子元素
            const children = Array.from(tabWrap!.children);
            // 当前劫持元素的索引值
            const sourceIndex = children.indexOf(source_node);
            // 覆盖到谁上面的索引值
            const targetIndex = children.indexOf(this.overTab);
            if (!(this.eTabs.fixed && (targetIndex === 0 || sourceIndex === 0))) {
                if (sourceIndex < targetIndex) {
                    // insertBefore(要插入的节点，在谁前面)
                    // 从左向右拖动
                    tabWrap.insertBefore(source_node, this.overTab.nextElementSibling);
                } else {
                    console.log('insertBefore', tabWrap, source_node, this.overTab)
                    // 从右向左拖动,this.overTab为null时放在最后面
                    tabWrap.insertBefore(source_node, this.overTab);
                }
                // 传入改变位置的两个元素，比较差异，执行动画
                this.last([this.overTab, source_node]);
            }
        }, false);
        tabWrap.addEventListener("dragend",(e: any) => {
            setTimeout(() => {
                this.tab!.classList.remove(`${this.eTabs.names.tabContainerClassName}-dragging`);
            }, 0);
        }, false);
    }
}

